//
//  MTUpdatePasswordController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/11.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory
import YPNavigationBarTransition
import RxSwift
import RxCocoa
import Moya
import Result

class MTUpdatePasswordController: BaseViewController {
    
    /// MTProvider
    private lazy var provider: MTProvider<UserCenterApi> = {
        return MTProvider<UserCenterApi>(plugins: [])
    }()
    
    private let disposeBag = DisposeBag()
    
    var param: [String: String] = [:]

    lazy var bgView: UIView = {
        let view = UIView()
        view.backgroundColor = .white
        return view
    }()
    /// 密码 TextField
    lazy var pwdTextField: UITextField = {
        let pwdTF = createTextField(withPlaceholder: "请输入新密码")
        pwdTF.keyboardType = .alphabet
        pwdTF.isSecureTextEntry = true
        return pwdTF
    }()
    /// 密码 TextField
    lazy var checkPwdTextField: UITextField = {
        let pwdTF = createTextField(withPlaceholder: "请再次输入新密码")
        pwdTF.keyboardType = .alphabet
        pwdTF.isSecureTextEntry = true
        return pwdTF
    }()
    
    lazy var showPwdButton1: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "hiddenpwd"), for: .normal)
        button.setImage(UIImage(named: "showpwd"), for: .selected)
        button.addTarget(self, action: #selector(updatePasswordController(showBtnClick:)), for: .touchUpInside)
        return button
    }()
    
    lazy var showPwdButton2: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "hiddenpwd"), for: .normal)
        button.setImage(UIImage(named: "showpwd"), for: .selected)
        button.addTarget(self, action: #selector(updatePasswordController(showBtnClick:)), for: .touchUpInside)
        return button
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        title = "修改密码"
        initializeUI()
    }
    
    /// 完成按钮
    lazy var commitButton: UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.theme.main
        btn.setTitle("完成", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.addTarget(self, action: #selector(updatePasswordController(commitBtnClick:)), for: .touchUpInside)
        return btn
    }()
}

extension MTUpdatePasswordController {
    private func initializeUI() {
        view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(dismissKeyBoard)))
        view.addSubview(bgView)
        view.addSubview(commitButton)
        bgView.addSubview(pwdTextField)
        bgView.addSubview(checkPwdTextField)
        bgView.addSubview(showPwdButton1)
        bgView.addSubview(showPwdButton2)
        
        bgView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(NavigationBarHeight+StatusBarHeight)
            make.height.equalTo(128)
        }
        
        pwdTextField.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.top.equalTo(bgView)
            make.height.equalTo(64)
            make.width.equalTo(ScreenWidth)
        }
        
        showPwdButton1.snp.makeConstraints { (make) in
            make.right.equalTo(view).offset(-20)
            make.width.height.equalTo(33)
            make.centerY.equalTo(pwdTextField)
        }
        
        
        checkPwdTextField.snp.makeConstraints { (make) in
            make.left.equalTo(10)
            make.top.equalTo(pwdTextField.snp.bottom)
            make.height.equalTo(64)
            make.width.equalTo(ScreenWidth)
        }
        
        showPwdButton2.snp.makeConstraints { (make) in
            make.right.equalTo(view).offset(-20)
            make.width.height.equalTo(33)
            make.centerY.equalTo(checkPwdTextField)
        }
        
        commitButton.snp.makeConstraints { (make) in
            make.left.equalTo(20)
            make.right.equalTo(-20)
            make.height.equalTo(50)
            make.bottom.equalTo(-ScreenBottomExtraOffset-20)
        }
        
    }
    
    @objc private func dismissKeyBoard() {
        pwdTextField.endEditing(true)
        checkPwdTextField.endEditing(true)
    }
    
    private func createTextField(withPlaceholder placeholder: String) -> UITextField {
        let tf = UITextField()
        tf.font = PingFangSCRegularFont(15)
        tf.textColor = .black
        tf.tintColor = .black
        
        let astr = NSMutableAttributedString(string: placeholder)
        astr.setAttributes([NSAttributedString.Key.foregroundColor: UIColor(hex:0x9b9b9b)], range: NSMakeRange(0, astr.length))
        tf.attributedPlaceholder = astr
        
        let line = UIView()
        line.backgroundColor = UIColor(hex:0xd8d8d8)
        tf.addSubview(line)
        
        line.snp.makeConstraints { (make) in
            make.right.bottom.equalTo(tf)
            make.left.equalTo(tf).offset(-10)
            make.height.equalTo(0.5)
        }
        return tf
    }
}

extension MTUpdatePasswordController {
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .default
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTUpdatePasswordController {
    private func updatePasswordController(commitBtnClick sender: UIButton) {
        if pwdTextField.text?.count == 0 || checkPwdTextField.text?.count == 0 {
            AlertManager.presentAlertView(message: "请填写密码")
            return
        }
        
        if pwdTextField.text != checkPwdTextField.text {
            AlertManager.presentAlertView(message: "密码填写不一致")
            return
        }
        
        self.param["password"] = pwdTextField.text
        provider.rx.originRequest(.resetPwd(parameter: self.param)).subscribe(onNext: { [weak self] (result, isCache) in
            switch result {
                
            case .success(let response):
                if let datas = try? response.mapJSON() as? [String: Any], let code = datas["code"] as? Int {
                    
                    if code == 200 {
                        UserCenter.default.logout()
//                        let vc: MTVerifyCodeController = MTVerifyCodeController()
//                        vc.phone = weakself.phoneTxt.text ?? ""
//                        vc.needSetPwd = weakself.titleStr == "请输入绑定的手机号"
//                        weakself.navigationController?.pushViewController(vc, animated: true)
                    } else {
                        AlertManager.presentAlertView(message: datas["message"] as? String ?? "")
                    }
                }
                break
                
            case .failure(_):
                AlertManager.presentAlertView(message: "网络错误")
                break
            }
                           
        }).disposed(by: self.disposeBag)
    }
    
    private func updatePasswordController(showBtnClick sender: UIButton) {
        showPwdButton1.isSelected = !showPwdButton1.isSelected
        showPwdButton2.isSelected = !showPwdButton2.isSelected
        pwdTextField.isSecureTextEntry = !showPwdButton1.isSelected
        checkPwdTextField.isSecureTextEntry = !showPwdButton1.isSelected
    }
}

